package com.mediastory.spsserver.content.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mediastory.spsserver.category.service.CategorySvc;
import com.mediastory.spsserver.contFile.service.ContFileSvc;
import com.mediastory.spsserver.content.domain.Content;
import com.mediastory.spsserver.content.service.ContentSvc;
import com.mediastory.spsserver.customer.service.CustomerSvc;

/**
 * @author Jaewon Choi
 */

@Controller
@RequestMapping(value={"/content"})
public class ContentCtrl {
	
	private final Logger logger = Logger.getLogger(getClass());
	
	@Autowired
	private ContentSvc contentSvc;
	
	@Autowired
	private ContFileSvc contFileSvc;
	
	@Autowired
	private CategorySvc categorySvc;
	
	@Autowired
	private CustomerSvc customerSvc;

	/**
	 * 목록 보기
	 * */
	@RequestMapping(value={"/list.do"})
	public Map<String, Object> list(HttpServletRequest request, HttpSession session) throws Exception {
		Map<String, Object> condition = new HashMap<String, Object>();
		//검색 parameter
		String name = ServletRequestUtils.getStringParameter(request, "name");
		String title = ServletRequestUtils.getStringParameter(request, "title");
		String startDate = ServletRequestUtils.getStringParameter(request, "startDate");
		String endDate = ServletRequestUtils.getStringParameter(request, "endDate");
		String categoryIdx = ServletRequestUtils.getStringParameter(request, "categoryIdx");
		
		//customerIdx
		Integer cIdx = (Integer)session.getAttribute("cIdx");
		
		condition.put("name", name);
		condition.put("title", title);
		condition.put("startDate", startDate);
		condition.put("endDate", endDate);
		condition.put("categoryIdx", categoryIdx);
		condition.put("cIdx", cIdx);

		//페이징 처리 parameter
		int maxnum = ServletRequestUtils.getIntParameter(request, "maxnum", 10);
		int page = ServletRequestUtils.getIntParameter(request, "page", 1);
		condition.put("maxnum", maxnum);
		condition.put("page", (page-1)*maxnum);
		
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.putAll(contentSvc.findbyListPaging(condition));

		// 권한
		String userRole = (String)session.getAttribute("userRole");
		if(userRole.equals("ROLE_ADMIN")) {
			resultMap.put("categoryList", categorySvc.findbyList(null));
		} else {
			resultMap.put("categoryList", categorySvc.findbyList(condition));
		}
		
		resultMap.put("maxnum", maxnum);
		resultMap.put("page", page);
		
		return resultMap;
	}

	/**
	 * 상세 보기
	 * */
	@RequestMapping(value={"/detail.do"})
	public Map<String, Object> detail(HttpServletRequest request, HttpSession session, @RequestParam(required=true, value="idx")  Integer idx) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		//customerIdx
		Integer cIdx = (Integer)session.getAttribute("cIdx");
		
		//카테고리 검색 조건
		Map<String, Object> condition = new HashMap<String, Object>();
		condition.put("cIdx", cIdx);
		condition.put("idx", idx);

		resultMap.put("content", contentSvc.findby(condition));
		
		//콘텐츠 상세 보기일 경우 콘텐츠의 id를 조건으로 카테고리를 조회하여 어느 카테고리에 포함는지를 표시하기 위함. 
		condition.put("contentIdx", idx);
		
		//카테고리 목록
		resultMap.put("categoryList", categorySvc.findbyList(condition));
		
		//고객 idx로 app id 목록 조회
		resultMap.put("customerInfo", customerSvc.findby(cIdx));
		
		//콘텐츠 파일 조회
		condition.put("contIdx", idx);
		
		//메인 이미지 파일 목록
		condition.put("fileType", "mainImg");
		resultMap.put("mainImgs", contFileSvc.findbyList(condition));
		
		return resultMap;
	}
	
	/**
	 * 등록,수정 폼
	 * */
	@RequestMapping(value={"/form.do"})
	public Map<String, Object> form(HttpServletRequest request, HttpSession session) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		
		//customerIdx
		Integer cIdx = (Integer)session.getAttribute("cIdx");
		
		//카테고리 검색 조건
		Map<String, Object> condition = new HashMap<String, Object>();
		
		int idx = ServletRequestUtils.getIntParameter(request, "idx", 0);
		if(idx != 0){
			
			condition.put("cIdx", cIdx);
			condition.put("idx", idx);

			resultMap.put("content", contentSvc.findby(condition));
			
			//콘텐츠 상세 보기일 경우 콘텐츠의 id를 조건으로 카테고리를 조회하여 어느 카테고리에 포함는지를 표시하기 위함. 
			condition.put("contentIdx", idx);
			
			//콘텐츠 파일 조회
			condition.put("contIdx", idx);
			
			//메인 이미지 파일 목록
			condition.put("fileType", "mainImg");
			resultMap.put("mainImgs", contFileSvc.findbyList(condition));
		}
		
		//카테고리 목록
		//resultMap.put("categoryList", categorySvc.findbyList(condition));
		// 권한
		String userRole = (String)session.getAttribute("userRole");
		if(userRole.equals("ROLE_ADMIN")) {
			resultMap.put("categoryList", categorySvc.findbyList(condition));
		} else {
			condition.put("cIdx", cIdx);
			resultMap.put("categoryList", categorySvc.findbyList(condition));
		}
		
		//고객 idx로 app id 목록 조회
		resultMap.put("customerInfo", customerSvc.findby(cIdx));
		
		return resultMap;
	}
	
	/**
	 * 콘텐츠 등록/수정
	 * */
	@RequestMapping(value={"/submit.do"}, method=RequestMethod.POST)
	public String submit(Content content, HttpServletRequest request, HttpSession session) throws Exception {
		//customerIdx
		Integer cIdx = (Integer)session.getAttribute("cIdx");
		String userId = (String)session.getAttribute("userId");
		String ip = request.getRemoteAddr();
		content.setcIdx(cIdx);
		
		if(content.getIdx() != null){
			if(content.getReward() == null) {
				content.setReward(0);
			}
			contentSvc.modify(content);
		}else{
			if(content.getReward() == null) {
				content.setReward(0);
			}
			contentSvc.add(content);
		}

		return "content/result";
	}
	
	/**
	 * 콘텐츠 삭제
	 * */
	@RequestMapping(value={"/remove.do"}, method=RequestMethod.POST)
	public String remove(HttpServletRequest request, HttpSession session) throws Exception {
		String userId = (String)session.getAttribute("userId");
		String ip = request.getRemoteAddr();
		
		//customerIdx
		Integer cIdx = (Integer)session.getAttribute("cIdx");
		
		int[] idx = ServletRequestUtils.getIntParameters(request, "idx");
		
		Map<String, Object> condition = new HashMap<String, Object>();
		
		condition.put("modifiedId", userId);
		condition.put("modifiedIp", ip);
		condition.put("idx", idx);
		condition.put("cIdx", cIdx);
		
		contentSvc.remove(condition);
		return "content/result";
	}
	
	/**
	 * 콘텐츠명 중복 체크
	 * */
	@RequestMapping(method=RequestMethod.POST, value="/chkDupl")
	public @ResponseBody Map<String, Object> chkContNm(HttpSession session, @RequestParam(required=true, value="idx")  Integer idx, @RequestParam(required=true, value="chkName")  String name) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			Map<String, Object> condition = new HashMap<String, Object>();
			
			//customerIdx
			Integer cIdx = (Integer)session.getAttribute("cIdx");
			condition.put("cIdx", cIdx);
			condition.put("idx", idx);
			condition.put("chkName", name);
			Integer resultCnt = contentSvc.findbyChkNm(condition);
			
			String result = "true";
			if(resultCnt != null && resultCnt > 0){
				result = "false";
			}
			
			resultMap.put("resultCode", "200");
			resultMap.put("result", result);
		} catch (Exception e) {
			// TODO: handle exception
			//e.printStackTrace();
			logger.error(e.getMessage(), e);
			resultMap.put("resultCode", "500");
			resultMap.put("errMsg", "Error");
		}

		return resultMap;
	}

}